

const app = getApp()

import { Base } from '../../utils/base.js';
var base = new Base();//初始化对象

var store_id = 9;

var listscroll = [] ;
var isScrolling = false;  //是否正在处理滚动事件，避免一次滚动多次触发

var cate_id_arr = []; 
var _load = true; //是否首次加载scorll位置
var is_swiper = false; //是否存在轮播图
var order_mk_id = 0; //参与的满减活动ID
Page({
  data: {
    hasUserInfo: false,  //是否登录
    TabCur: 0,
    MainCur: 0,
    VerticalNavTop: 0,
    list: [],   //菜品分类信息
    listscroll:[], //菜品分类位置
    load: true,
    foodautoplay:true,

    store:{},  //门店信息
    cart:{},  //购物车
    cart_cate:[],  //购物车分类数量
    price:0,   //订单价格
    package_price:0,  //餐盒费
    coupon_price:0,  //优惠金额
    total_num : 0,  //桌台
    activity_price:0, //活动优惠

    //滑动具体
    'topMt':'',
    'navMt':'calc(100vh - 375rpx)',
    //广告位
    cardCur: -1, //默认变大选项
    swiperList: [],

    //活动
    //满减活动
    manjian:[]
  },

  

  onLoad( option ) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    //判读是否登录
    let userInfo = wx.getStorageSync('userInfo');
    if( userInfo ){
      this.setData({
        hasUserInfo: true
      })
    }

    let that = this;

    //获取桌台信息
    this.table(option , function(){

      //获取菜品信息
      that.getGoodsList();

      //获取当前门店信息
      that.getStoreInfo();
      
      //获取当前门店满减活动
      that.getStoreActivity();
      

      //获取广告位
      that.getStoreAdvert();
      
    });


    
    
  },
  onReady() {
    // wx.hideLoading()
  },

  //获取桌台信息
  table( option ,_call ){

    //设置桌台号
    wx.setStorageSync('table_num', 1);

    if (typeof _call == "function") {
      _call();
    }

  },

   /**
  * 弹出授权
  */
 bindGetUserInfo: function (e) {
  var that = this;
  app.wxlogin( function(ret){
    that.setData({
      hasUserInfo: true
    })
    console.log("login_call");
    
    that.order();
  });
},

  //获取当前门店信息
  getStoreInfo(){

    let that = this;
    base._ajax(base.Conf.serverUrl + "v1/store/getStoreInfo", { 
      'store_id' : store_id
    }, 'post', function (ret) {
      if(ret.errcode === 0){
        //门店信息
        that.setData({
          store:ret.data
        })
        wx.setStorageSync('store', ret.data);
      }
    });
  },

  //获取菜品信息
  getGoodsList(){

    let that = this;
    base._ajax(base.Conf.serverUrl + "v1/store/getItemInfo", { 
      'store_id' : store_id
    }, 'post', function (ret) {
      if(ret.errcode === 0){
        //循环
        cate_id_arr = [];
        ret.data.category.forEach(function(v){
          cate_id_arr.push(v.id);
        })
        wx.setStorageSync('goods', ret.data.goods);
        that.setData({
          list: ret.data,
          TabCur: ret.data.category[0]['id']
        })

        wx.hideLoading()
      }
    });
  },

  //获取门店活动
  getStoreActivity:function(){

    let that = this;
    base._ajax(base.Conf.serverUrl + "v1/store/getActivity", { 
      'store_id' : store_id,
      'id'  : 1
    }, 'post', function (ret) {
      if(ret.errcode === 0){

        //设置满减活动
        that.setData({
          manjian:ret.data.manjian
        })
      }
    });

  },
  //获取广告位
  getStoreAdvert:function(){
    let that = this;
    base._ajax(base.Conf.serverUrl + "v1/getAdvert", { 
      'store_id' : store_id,
      'id'  : 1
    }, 'post', function (ret) {
      if(ret.errcode === 0){

        if(ret.data && ret.data.length > 0){
          is_swiper = true;
          that.setData({
            swiperList:ret.data,
            'navMt':'calc(100vh - 380rpx)',
          })

        } else{
          is_swiper = false;
          that.setData({
            swiperList:ret.data,
            'navMt':'calc(100vh - 306rpx)',
          })

        }
        
      }
    });
  },

  //提交订单
  order:function(){
    let that = this;

    //校验token是否正常
    let userInfo = wx.getStorageSync('userInfo');
    if( !userInfo ){
      base._toast('用户信息过期，请重新授权');

      that.setData({
        hasUserInfo:false
      })
      return false;
    }

    //判断购物车数量
    let cart = that.data.cart;
    if( Object.keys(cart).length <=0){
      base._toast('请选择菜品');
      return false;
    }

    base._ajax(base.Conf.serverUrl + "v1/checkToken", {
      token :userInfo.token
    }, 'post', function (ret) {
      
      if( ret.errcode == 0){
        let store = wx.getStorageSync('store');
        
        wx.navigateTo({
          url: "/pages/pay/index" ,
          success:function(res){
            res.eventChannel.emit('cart', { cart: that.data.cart , store_id: store.store_id , order_mk_id:order_mk_id})
          }
        })

      } else {
        that.setData({
          hasUserInfo:false
        })
        return true;

      }
    })
    

  },

  
  // 添加购物车
  addCart:function(e){
    //获取商品ID
    var gid = e.currentTarget.dataset.gid;
    var sku_id = e.currentTarget.dataset.sku_id;
    //获取购物车信息
    let cart = this.data.cart;
    //所有菜品信息
    let goods = this.data.list.goods;
    // console.log(goods);
    let card_gid = gid ;
    //购物车无商品时
    
    if( typeof cart[card_gid] =='undefined'  ||  cart[card_gid].length ==0 ){

      //循环找到当前菜品
      goods.forEach(function(v,i){
          //判断是当前菜品
          if( v.food_code == gid ){

            cart[card_gid] = [];
            let sku = v.sku;
            sku.forEach(function(sv,si){
              //判断是否是当前sku属性
              if(sv.id ==sku_id){
                //循环sku 判断库存是否满足
                if( sv.number < 1 ){
                    base._toast('库存不足');
                    return false;
                }

                //加入到购物车中
                cart[card_gid] = {
                  [sku_id]:{
                    food_code:v.food_code,  //菜品标识
                    goods_num:1, //添加到购物车数量
                    sku_id   : sv.id,
                    member_price: sv.member_price,  //售价  
                    coupon_price: 0,         //优惠金额  如第二份半价时  优惠金额
                    package_price:sv.package_price,  //餐盒费
                    goods_name:v.title,
                    mk_id : 0,   //活动ID
                    cate_id :v.cate_id
                  }
                };
                // cart[card_gid]["'"+sku_id+"'"] = 
                
              }
                
            });
          }
      });
      
    } else {
      //购物车有商品时增加商品数量
      // let goods_num = cart[card_gid].goods_num;
      cart[card_gid][sku_id].goods_num++;
      
    }


    //重新赋值购物车数据
    this.setData({
      'cart': cart
    });
    //当前门店购物车信息
    wx.setStorageSync('cart', cart);
    //重新计算购物车价格
    this.calcCartPrice();

  },
  // 删除购物车
  delCart:function(e){
    //获取商品ID
    var gid = e.currentTarget.dataset.gid;
    var sku_id = e.currentTarget.dataset.sku_id;

    //获取购物车信息
    let cart = this.data.cart;
    //所有菜品信息
    let goods = this.data.list.goods;
    // console.log(goods);

    let card_gid = gid;

    //购物车无商品时
    if( typeof cart[card_gid] !='undefined' ){

      let goods_num = cart[card_gid][sku_id].goods_num;
      goods_num--;
      if( goods_num > 0){
        cart[card_gid][sku_id].goods_num--;
      } else {
        //删除当前属性
        delete cart[card_gid][sku_id];
        //判断当菜品是否还有其他属性菜品， 如果没有则删除当前商品
        console.log(Object.keys(cart[card_gid]).length);
        if( Object.keys(cart[card_gid]).length <=0){
          delete cart[card_gid];
        }
      }
      
    }

    //重新赋值购物车数据
    this.setData({
      'cart': cart
    });
    //当前门店购物车信息
    wx.setStorageSync('cart', cart);
    //重新计算购物车价格
    this.calcCartPrice();

  },

  //清空购物车
  clearCart:function(e){

    let cart = {};
    //重新赋值购物车数据
    this.setData({
      
      modalName: '',
      tabBarmodal:false,
      'cart': cart
    });
    //当前门店购物车信息
    wx.setStorageSync('cart', cart);
    //重新计算购物车价格
    this.calcCartPrice();

  },

  //重新计算购物车价格
  calcCartPrice:function(){
    //获取购物车信息
    let cart = this.data.cart;
    console.log(cart);
    //计算购物车价格及优惠券价格
    let total_num = 0; //总数量
    let price =0;   //订单价格
    let package_price = 0;  //餐盒费
    let coupon_price  =  0;  //菜品优惠金额
    let activity_price = 0; //活动优惠金额

    let cart_cate = {};
    for(var i in cart) {
      let sku = cart[i];
      for(var si in sku) {
        total_num += (sku[si].goods_num *1) ;
        price += (sku[si].member_price * 1) * sku[si].goods_num  ;   //金额 = 会员金额 * 数量
        package_price += (sku[si].package_price * 1) * sku[si].goods_num  ;  //餐盒费 = 餐盒费 * 数量
        coupon_price += sku[si].coupon_price  *1 ;   //优惠金额

    
        
        
        let cate_id = sku[si].cate_id ;
        if( !cart_cate[cate_id] ){
          cart_cate[cate_id] = sku[si].goods_num
        } else {
          cart_cate[cate_id] =  cart_cate[cate_id]  + sku[si].goods_num;
        }
      };
    };

    price = price.toFixed(2) ;    

    //判断是否满足满减活动
    let mj = this.data.manjian;
    if( typeof mj.mk_info !='undefined'){
      let mk_info = mj.mk_info;
      //循环判断是否满足条件
      mk_info.forEach(function(v){
          console.log(v);
          let man_money = v.man * 1;
          if( price > man_money ){
            order_mk_id = v.mk_id;
            activity_price = (v.money) * 1;
          }
      });
    }


    console.log(price);
    console.log(package_price);
    console.log(coupon_price);
    console.log(activity_price);

    console.log(cart_cate);
    this.setData({
      total_num:total_num,
      price:price,
      package_price:package_price,
      coupon_price:coupon_price,
      activity_price:activity_price,

      cart_cate:cart_cate
      
    })


  },
  

  //跳转
  link_page:function(e){

    //获取当前list 索引
    var type = e.currentTarget.dataset.type;
    var url = e.currentTarget.dataset.url;

    base._link_page(url,type);

  },


  //滑动菜品选择
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      MainCur: e.currentTarget.dataset.id
    })
  },
  VerticalMain(e) {
    
    let that = this;
    let listgoods = this.data.list;
    let list = listgoods.goods;
    
    let tabHeight = 0;

    //判断是否正在处理滚动事件
    if(isScrolling===true){
      console.log('正在处理滚动事件，防止触发多次造成卡顿')
      return true;
    }
    console.log('VerticalMain触发')
    isScrolling = true;
      

    //首次滑动，加载分类位置
    if (_load) {
      list.forEach(function(val , i){
        let view = wx.createSelectorQuery().select("#main-" + val.cate_id);
        view.fields({
          size: true
        }, data => {
          listscroll[i] ={};
          listscroll[i].cate_id = val.cate_id;
          listscroll[i].top = tabHeight;
          tabHeight = tabHeight + data.height;
          listscroll[i].bottom = tabHeight;     
        }).exec();
      })

      _load = false;

      
    }


    //上滑下滑 全屏展示菜品
    console.log(is_swiper);
    console.log("is_swiper");
    if( is_swiper ){
      if(e.detail.scrollTop<30){
        that.setData({
          'topMt':'transform: translate(0px,0px);transition: transform 0.25s;',
          'navMt':'calc(100vh - 380rpx)',
          foodautoplay:true,
        })
      } else {
        that.setData({
          'topMt':'transform: translate(0px,-190px);transition: transform 0.35s;',
          'navMt':'calc(100vh - 134rpx)',
          foodautoplay:false,
        })
      }

    }
    

    //当前滚动位置
    let scrollTop = e.detail.scrollTop + 110;
    let listscroll2 = listscroll;

    let _VerticalNavTop = 0;
    let _TabCur = 0;
    // 循环判断当前滚动位置 在哪个分类下
    listscroll2.forEach(function(val , i){

      if (scrollTop > listscroll2[i].top && scrollTop < listscroll2[i].bottom) {
        
        let catelen = cate_id_arr;
        
        _VerticalNavTop = catelen.indexOf(listscroll2[i].cate_id)*15;
        _TabCur = listscroll2[i].cate_id;
        //滚动事件关闭
        isScrolling = false;
        return true;
      }


    })

    console.log('执行nav_top');
    if( _TabCur ){
      that.setData({
        VerticalNavTop: _VerticalNavTop,
        TabCur: _TabCur
      })
    }
    
  

    //滚动事件关闭
    isScrolling = false;
  },


  //菜品滚动到顶部时触发
  VerticalMainTop(e) {
  
    console.log('触发VerticalMainTop');
    // 有轮播图时才滚动
    if( is_swiper ){
      this.setData({
        'topMt':'transform: translate(0px,0px);transition: transform 0.25s;',
        'navMt':'calc(100vh - 38rpx)',
      })   
    } 
  },



  // 满减活动弹框
  showModal(e) {
    
    this.setData({
      modalName: e.currentTarget.dataset.target,
      tabBarmodal:true
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null,
      tabBarmodal:false
    })
  },
})